package com.maotai.bl.dao;

import javax.annotation.Resource;

import org.apache.ibatis.mapping.*;
import org.apache.ibatis.mapping.MappedStatement.Builder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author 张羽
 * 功能 dao基类
 * date 2016-5-9
 */
//此处必须加事物注解,否则事物失效
@Transactional
public class CommonDao extends SqlSessionDaoSupport {
	
     @Resource
     public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory){
         super.setSqlSessionFactory(sqlSessionFactory);
     }
     
     @Resource
     public JdbcTemplate jdbcTemplate;
     
     
     public MappedStatement copyFromstatement(MappedStatement ms,SqlSource newsqlSource){
         Builder builder=new Builder(ms.getConfiguration(), ms.getId(),newsqlSource, ms.getSqlCommandType());
         builder.resource(ms.getResource());
         builder.fetchSize(ms.getFetchSize());
         builder.statementType(ms.getStatementType());
         builder.keyGenerator(ms.getKeyGenerator());
         //builder.keyProperty(ms.getKeyProperties());
         builder.timeout(ms.getTimeout());
         builder.parameterMap(ms.getParameterMap());
         builder.resultMaps(ms.getResultMaps());
         builder.cache(ms.getCache());
         MappedStatement newms=builder.build();
         return newms;
     }
     
     
     public BoundSql copyFromboundsql(MappedStatement ms,BoundSql boundSql,String newsql){
         BoundSql newBoundSql=new BoundSql(ms.getConfiguration(), newsql, boundSql.getParameterMappings(), boundSql.getParameterObject());
         for (ParameterMapping mapping: boundSql.getParameterMappings()){
             String prop=mapping.getProperty();
             if(boundSql.hasAdditionalParameter(prop)){
                 newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
             }
        }
         return newBoundSql;
     }
}